﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;

namespace DMOZ
{
    public partial class Form1 : Form
    {
        private string savepath = System.Configuration.ConfigurationSettings.AppSettings["savepath"];
        Dictionary<int, string> allArea = new Dictionary<int, string>();
        public Form1()
        {
            InitializeComponent();
            allArea.Add(138, "上海");
            allArea.Add(180, "云南");
            allArea.Add(158, "内蒙古");
            allArea.Add(137, "北京");
            allArea.Add(185, "台湾");
            allArea.Add(160, "吉林");
            allArea.Add(178, "四川");
            //    allArea.Add(186, "国外");
            allArea.Add(139, "天津");
            allArea.Add(168, "宁夏");
            allArea.Add(164, "安徽");
            allArea.Add(171, "山东");
            allArea.Add(157, "山西");
            allArea.Add(175, "广东");
            allArea.Add(176, "广西");
            allArea.Add(182, "新疆");

            allArea.Add(162, "江苏");
            allArea.Add(170, "江西");
            allArea.Add(156, "河北");
            allArea.Add(172, "河南");
            allArea.Add(163, "浙江");
            allArea.Add(177, "海南");
            allArea.Add(173, "湖北");

            allArea.Add(174, "湖南");

            allArea.Add(184, "澳门");
            allArea.Add(166, "甘肃");
            allArea.Add(169, "福建");
            allArea.Add(179, "贵州");
            allArea.Add(161, "辽宁");

            allArea.Add(181, "西藏");
            allArea.Add(140, "重庆");

            allArea.Add(165, "陕西");
            allArea.Add(167, "青海");

            allArea.Add(183, "香港");
            allArea.Add(159, "黑龙江");
        }
      
        private int  getAreaID(string url)
        {
           
            

            if (url.ToLower().IndexOf("http://") > -1)
            {
                url = url.Remove(0, 7);

            }
            if (url.ToLower().LastIndexOf("/") > -1)
            {
                url = url.Remove(url.ToLower().LastIndexOf("/"));
            }
            int i = 0;
            int k = 0;
            while (i < url.Length)
            {
                if (url[i] == '/')
                {
                    ++k;
                }
                i++;
            }
            if (k == 0)
            {

            }
            else if (k == 1)
            {

                url = url.Remove(url.LastIndexOf("/"), 1);
            }
            else
            {
                int n = url.IndexOf('/');
                url = url.Remove(n);
            }
            string cur_area = Util.getArea(url);
            if (String.IsNullOrEmpty(cur_area))
                return 186;
            foreach(KeyValuePair<int,string> kp in allArea)
            {
               if(cur_area.IndexOf(kp.Value)>-1)
                {
                    return kp.Key;
                }
            }
            return 186;
           
        }
        private void Generate(string Content)
        {
            string file_path = savepath + "gttol_post.sql";
             
            if (File.Exists(file_path))
            {
                File.Delete(file_path);
            }
            System.IO.FileStream fs = System.IO.File.Create(file_path);
            Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(Content);
            fs.Write(bContent, 0, bContent.Length);
            fs.Close();
            fs = null;
        }
        private void GeneratePostID(string Content)
        {
            string file_path = savepath + "postId.txt";

            if (File.Exists(file_path))
            {
                File.Delete(file_path);
            }
            System.IO.FileStream fs = System.IO.File.Create(file_path);
            Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(Content);
            fs.Write(bContent, 0, bContent.Length);
            fs.Close();
            fs = null;
        }
        private string[] ReadPostIDFromPostIDTXT()
        {
            string[] result = null;
            string file_path = savepath + "postId.txt";
            if (File.Exists(file_path))
            {
                System.IO.FileStream fs = System.IO.File.OpenRead(file_path);
                StreamReader reader = new StreamReader(fs);
                result = reader.ReadToEnd().Split('\t');
                reader.Close();
                fs.Close();
                reader = null;
                fs = null;
                //File.Delete(file_path);
            }

            return result;

        }
        private void GenerateUpdateAreaCount(string Content)
        {
            string file_path = savepath + "gttol_areacount.sql";
            if (File.Exists(file_path))
            {
                File.Delete(file_path);
            }
            System.IO.FileStream fs = System.IO.File.Create(file_path);
            Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(Content);
            fs.Write(bContent, 0, bContent.Length);
            fs.Close();
            fs = null;
        }
       
        private int getRand(int start,int end)
        {
            Random rand = new Random(DateTime.Now.Second);
            return rand.Next(start, end);
        }
        private void btnRun_Click(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(txtRegex.Text.Trim()))
                return;
                if(String.IsNullOrEmpty(txtUrl.Text.Trim()))
                return;
           string strRegex = txtRegex.Text.Trim();
            string strUrl =txtUrl.Text.Trim();
            // txtResult.Text = allArea.Count.ToString();//U
            StringBuilder sbuild = new StringBuilder();
            StringBuilder postIDBuidler = new StringBuilder();
             int lastPostId;
             if (int.TryParse(txtLastPostID.Text.Trim(), out lastPostId))
             {
               
                 if (lastPostId > 1)
                 {

                     Client client = new Client(strUrl, strRegex);
                     List<Page> content = client.Request();
                     if (client.Success)
                     {
                         foreach (Page page in content)
                         {
                             //if (page.url.IndexOf("http") > -1)
                             //    page.url = page.url.Replace(@"http://", "");
                             //if (page.url.IndexOf("www") > -1)
                             //    page.url = page.url.Replace(@"www.","");

                             //page.url = page.url.Substring(0, page.url.IndexOf(@"."));

                             ++lastPostId;
                             /*插入帖子*/
                             string insert_post = string.Format("INSERT INTO `wp_posts`(`ID`,`post_author`,`post_date`,`post_date_gmt`,`post_content`,`post_title`,`post_excerpt`,`post_status`,`comment_status`,`ping_status`,`post_password`,`post_name` ,`to_ping`,`pinged`,`post_modified`,`post_modified_gmt`,`post_content_filtered` ,`post_parent` ,`guid` ,`menu_order`,`post_type` ,`post_mime_type`,`comment_count`,`robotsmeta` ) VALUES( {0},1, '{1}', '{2}', '{3}\r\n', '{4}', '{5}', 'publish', 'open', 'open', '', '{6}', '', '', '{7}', '{8}', '', 0, '{9}', 0, 'post', '', 0, 'index,follow');", lastPostId, DateTime.Now.ToString(), DateTime.Now.ToString(),
                                 page.desc, page.title, page.desc, CHS2PinYin.GetAllPYLetters(page.title), DateTime.Now.ToString(), DateTime.Now.ToString(), "test");
                             sbuild.Append( insert_post + "\n");
                             /*插入网址*/
                             string insert_post_meta_url = string.Format("insert into `wp_postmeta`(`post_id`,`meta_key`,`meta_value`) values({0},'url', '{1}');", lastPostId, page.url);
                             sbuild.Append (insert_post_meta_url + "\n");
                             /*插入meta*/
                             string insert_post_meta_robotsmeta = string.Format("insert into `wp_postmeta`(`post_id`,`meta_key`,`meta_value`) values({0},'robotsmeta', 'index,follow');", lastPostId);
                             sbuild.Append ( insert_post_meta_robotsmeta + "\n");
                             /*插入hits*/
                             string insert_post_meta_hits = string.Format("insert into `wp_postmeta`(`post_id`,`meta_key`,`meta_value`) values({0},'hits', {1});", lastPostId, getRand(3, 700));
                             sbuild.Append (insert_post_meta_hits + "\n");
                             /*插入地区*/
                             string insert_post_tag = string.Format("insert into `wp_term_relationships`(`object_id`,`term_taxonomy_id`,`term_order`) values({0},{1},0);", lastPostId, getAreaID(page.url));
                                sbuild.Append(insert_post_tag + "\n");

                                postIDBuidler.Append(lastPostId + "\t ");

                         }
                         Generate(sbuild.ToString());
                         GeneratePostID(postIDBuidler.ToString());
                     }
                 }
                
             }
        }

        

        private void btnArea_Click(object sender, EventArgs e)
        {
            StringBuilder sbuild = new StringBuilder();
            int count, termID;
            string[] data = txtArea.Text.Split('\n');
            foreach(string s in data)
            {
                string[] d = s.Split(' ');
                if (int.TryParse(d[0], out count))
                {
                    
                    if (int.TryParse(d[1], out termID))
                    {
                        if (termID > 137 && termID < 187)
                        {
                        

                            string sqlarea = string.Format("update `wp_term_taxonomy` set count={0} where term_id={1};", count, termID);
                            sbuild.Append(sqlarea+"\n");
                        }
                    }
                }
            }
            GenerateUpdateAreaCount(sbuild.ToString());
           
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            int id =getAreaID(txtTestArea.Text.Trim());
            foreach(KeyValuePair<int,string>  s in allArea)
            {
                if (s.Key == id)
                {
                    MessageBox.Show(s.Value);
                    break;
                }
              
            }
            
        }

        private void btnStep1_Click(object sender, EventArgs e)
        {
            object o = DA_Base.ExecuteScalar(txtStep1.Text.Trim());
            if (o != null)
            {
                txtLastPostID.Text = o.ToString();
            }
        }
        private void get_category()
        {
            string sql = "SELECT * FROM `wp_term_taxonomy` tt LEFT JOIN `wp_terms` t ON tt.`term_id` = t.`term_id` WHERE taxonomy = 'category' AND parent =0";
            DataSet ds = DA_Base.RunReturnDS(sql);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
               
               
                int term_taxonomy_id = int.Parse(row["term_taxonomy_id"].ToString());
                string name = (row["name"].ToString());
                ComboBoxItem newItem = new ComboBoxItem();
                newItem.Text = name;
                newItem.Value =  term_taxonomy_id.ToString();
                this.comboBox1.Items.Add(newItem);

               // int parent = int.Parse(row["parent"].ToString());

                string sqlchild = string.Format(" SELECT * FROM `wp_term_taxonomy` tt LEFT JOIN `wp_terms` t ON tt.`term_id` = t.`term_id` WHERE taxonomy = 'category' AND parent ={0}", term_taxonomy_id);
                DataSet dsChild = DA_Base.RunReturnDS(sqlchild);
                foreach (DataRow rowchild in dsChild.Tables[0].Rows)
                {
                    int term_taxonomy_id_child = int.Parse(rowchild["term_taxonomy_id"].ToString());
                    // int parent = int.Parse(row["parent"].ToString());
                    string name_child = (rowchild["name"].ToString());

                    ComboBoxItem newItem_child = new ComboBoxItem();
                    newItem_child.Text = "——" + name_child;
                    newItem_child.Value = term_taxonomy_id_child.ToString();
                    this.comboBox1.Items.Add(newItem_child);
                }
            
            }
        }

        private void btngetcategory_Click(object sender, EventArgs e)
        {
            get_category();
        }

        private void btnStep4_Click(object sender, EventArgs e)
        {
            
             
             string[] idarr = ReadPostIDFromPostIDTXT();
             foreach (string s in idarr)
             {
                 if (!String.IsNullOrEmpty(s))
                 {
                     ComboBoxItem myItem = (ComboBoxItem)this.comboBox1.Items[this.comboBox1.SelectedIndex];

                     string sql = string.Format("insert into  `wp_term_relationships` (object_id,term_taxonomy_id,term_order) values({0},{1},0);", int.Parse(s), int.Parse(myItem.Value.ToString()));

                     DA_Base.ExecuteNonQuery(sql);
                 }
             }
        }
    }
}
